<template>
  <el-container>
    <el-header class="navbar">
      <div class="container">
        <a class="logo" href="/">
          <img src="/element-plus-logo.svg" alt="Element Plus Plus Logo" />
        </a>
        <div class="content">
          <el-menu mode="horizontal" :ellipsis="false">
            <el-menu-item index="1" @click="linkTo('/guide/design')"> 指南 </el-menu-item>
            <el-menu-item index="2" @click="linkTo('/component/button')"> 组件 </el-menu-item>
            <el-menu-item index="3" @click="linkTo('/guide/design')"> 资源 </el-menu-item>
          </el-menu>
          <a href="#">
            <icon icon="mdi:github" width="24" />
          </a>
          <el-button class="is-dark" @click="toggleDark()">
            <icon v-show="isDark" icon="mdi:moon-waxing-crescent" width="24" :style="{ transform: 'rotate(45deg)' }" />
            <icon v-show="!isDark" icon="mdi:white-balance-sunny" width="24" />
          </el-button>
        </div>
      </div>
    </el-header>
    <template v-if="enableHome">
      <home />
    </template>
    <el-container class="container" v-else>
      <sidebar />
      <el-main class="markdown">
        <el-scrollbar ref="scrollbarRef" @scroll="handleScroll">
          <el-row class="py-15 pl-10">
            <el-col :span="18">
              <Content ref="content" />
            </el-col>
            <el-col class="pl-10" :span="6">
              <nav ref="tocRef" class="toc-content" v-if="toc.length > 0">
                <h3 class="heading">目录</h3>
                <ul class="toc-items">
                  <li class="toc-item" v-for="(item, index) in toc" :key="index">
                    <a class="toc-link" :href="`#${item.slug}`" :title="item.title" @click="handleClickItem">{{
                      item.title
                    }}</a>
                  </li>
                </ul>
              </nav>
            </el-col>
          </el-row>
        </el-scrollbar>
      </el-main>
    </el-container>
  </el-container>
  <Debug />
</template>

<script setup lang="ts">
import _ from 'lodash';
import { ref, computed, onMounted } from 'vue';
import { useRouter, useData } from 'vitepress';
import { useDark, useToggle } from '@vueuse/core';
import { Icon } from '@iconify/vue';
import Home from './Home.vue';
import Sidebar from './Sidebar.vue';

const scrollbarRef = ref<{ $el: HTMLElement; setScrollTop: (scrollTop: number) => void }>();
const content = ref<{ $el: HTMLElement }>();

const [marker, toogleMarker] = useToggle(false);
const tocRef = ref<HTMLElement>();

const router = useRouter();
const { page, frontmatter } = useData();
const isDark = useDark();
const toggleDark = useToggle(isDark);

const enableHome = computed(() => !!frontmatter.value.home);

const maxScrollTop = computed(
  () => (scrollbarRef.value?.$el.querySelector('.el-scrollbar__view')?.scrollHeight || 0) + 60 - window.innerHeight,
);

onMounted(() => {
  setTimeout(() => {
    const current = content.value?.$el.querySelector(decodeURIComponent(document.location.hash)) as HTMLElement;

    scrollbarRef.value?.setScrollTop(current.offsetTop + 30);
  }, 150);
});

const linkTo = (path: string) => {
  router.go(path);
};

type Content = {
  href: string;
  anchor: HTMLElement;
  top: number;
};

const navs = computed(() => {
  const links = tocRef.value?.getElementsByClassName('toc-link');
  const items: Array<Content> = [];
  _.forEach(links, (link) => {
    const href = link.getAttribute('href');
    if (href !== null) {
      const anchor = content.value?.$el.querySelector(href) as HTMLElement;
      items.push({ href, anchor, top: anchor.offsetTop });
    }
  });
  return items;
});

const handleClickItem = (el: MouseEvent) => {
  const e = el.target as HTMLLinkElement;

  const target = content.value?.$el.querySelector(e.getAttribute('href') as string) as HTMLElement;

  if (target.offsetTop > maxScrollTop.value) {
    tocRef.value?.querySelector('.toc-item.active')?.classList.remove('active');
    tocRef.value?.querySelector(`a.toc-link[href="${e.getAttribute('href')}"]`)?.parentElement?.classList.add('active');
    history.replaceState(null, document.title, e.getAttribute('href'));
    toogleMarker(true);
  }

  scrollbarRef.value?.setScrollTop(target.offsetTop + 30);
};

let acitveNav: Content;

const handleScroll = ({ scrollTop }: { scrollTop: number }) => {
  console.log('scrollTop :>> ', scrollTop);
  if (scrollTop < 5) {
    history.replaceState(null, document.title, ' ');
  } else {
    for (const item of navs.value) {
      if (scrollTop >= item.top + 30) {
        acitveNav = item;
      }
    }

    if (marker.value === false) {
      tocRef.value?.querySelector('.toc-item.active')?.classList.remove('active');

      tocRef.value?.querySelector(`a.toc-link[href="${acitveNav.href}"]`)?.parentElement?.classList.add('active');

      history.replaceState(null, document.title, acitveNav.href);
    }
  }
  toogleMarker(false);
};

const toc = computed(() => page.value.headers);
</script>
